const koaRouter = require('koa-router')
const router = new koaRouter()

const checkIdExistByBody = require('../middleware/common/checkIdExistByBody')
const error = require('../middleware/common/error')
const login = require('../middleware/patient/login')
const get_sort = require('../middleware/patient/get_sort')
const get_medicine_lib = require('../middleware/patient/get_medicine_lib')
const create_buy_medicine = require('../middleware/patient/create_buy_medicine')
const get_buy_medicine = require('../middleware/patient/get_buy_medicine')
const get_doctor = require('../middleware/patient/get_doctor')
const create_foresee = require('../middleware/patient/create_foresee')
const get_foresee = require('../middleware/patient/get_foresee')
const online = require('../middleware/patient/online')

router.prefix('/patient')

router.post(['/login', '/'], async function (ctx, next) {
    ctx.checkBody('number').toInt();
    ctx.checkBody('pwd').len(2, 20).md5();
    await next();
}, error, login)


/**
 * 返回的一个数组，其元素是一对象，并且拥有 text 和 value 属性
 */

/** 获取分类列表 */
router.get(['/sort', '/drug_sort'], online, get_sort)

/** 获取仓库里的药品列表 */
router.get(['/medicine_list', '/medicine_lib'], online, get_medicine_lib)

/** 患者创建在线买药订单 */
router.post(['/create_buy_medicine', '/buy_medicine'], online, async function (ctx, next) {
    ctx.checkBody('medicine_lib_id').notEmpty().toInt();
    ctx.checkBody('amount').notEmpty().toInt().isInt({ min: 1 });
    await next();
}, error, create_buy_medicine)

/** 获取买药列表（查询） */
router.get(['/get_buy_medicine', '/buy_medicine'], online, error, get_buy_medicine)

/** 获取医师列表 */
router.get(['/get_doctor', '/doctor'], online, get_doctor)

/** 患者创建预约 */
router.post(['/create_foresee', '/foresee'], online, async function (ctx, next) {
    // 传入的是时间格式的字符串`2021-05-05T10:31`，将其转换成时间戳
    ctx.request.body.time = new Date(ctx.request.body.time).getTime()
    ctx.checkBody('time').toInt().isInt({ min: 0 });
    ctx.checkBody('memo').optional();
    ctx.checkBody('doctor_id').toInt().isInt();
    await next()
}, error, checkIdExistByBody('user', 'doctor_id'), create_foresee)

/** 患者获取预约列表 */
router.get(['/get_foresee', '/foresee'], online, get_foresee)

module.exports = router;